import moment from 'moment'
const app = getApp()

export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }

  let start = new Date(date.getFullYear(), 0, 1)
  let d = Math.round((date.valueOf() - start.valueOf()) / 86400000)

  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    w: Math.ceil((d + ((start.getDay() + 1) - 1)) / 7),
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymwdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

export function getWeekStartDate(time) {
  console.log(time)
  let data = time
  let year = Number(data.getFullYear())
  let month = Number(data.getMonth())
  let day = Number(data.getDate())
  let weekday = Number(data.getDay())
  return new Date(year, month, day + 1 - weekday);
}

export function getWeekEndDate(time) {
  let data = time
  let year = Number(data.getFullYear())
  let month =Number(data.getMonth())
  let day = Number(data.getDate())
  let weekday = Number(data.getDay())
  return new Date(year, month, day + 7 - weekday, 23, 59, 59, 999);
}

export function weekBegin(time) {
  time = moment(time)
  return time.week(time.week()).startOf('week').valueOf()
}

export function weekEnd(time) {
  time = moment(time)
  return time.week(time.week()).endOf('week').valueOf()
}

export function getDateBeginTimestamp(date) {
  return moment(moment(date).format('YYYY-MM-DD') + ' 00:00:00').unix() * 1000
}

export function getDateEndTimestamp(date) {
  return moment(moment(date).format('YYYY-MM-DD') + ' 23:59:59').unix() * 1000
}


export function isWorkerRole() {
  if(app.globalData.userInfo.roles){
    const one = app.globalData.userInfo.roles.find(e =>e.role === 'worker')
    if(one){
      return true;
    }
  }
  return false
}

export function alert(content) {
 dd.alert({
   content: content,
   buttonText: "确定"
  })
}
